<?php
/**
 *+------------------
 * Lflow
 *+------------------
 * Copyright (c) 2023~2030 gitee.com/liu_guan_qing All rights reserved.本版权不可删除，侵权必究
 *+------------------
 * Author: Mr.April(405784684@qq.com)
 *+------------------
 */
declare (strict_types=1);

namespace lflow\lib\util;

use lflow\lib\util\util\StringHelper;
use lflow\lib\util\WorkFlowException;

/**
 *
 * Json 处理帮助类
 * @author Mr.April
 * @since  1.0
 */
class JsonHelper
{

    /**
     * 检验JSON字符串
     *
     * @param $str
     *
     * @return bool
     */
    public static function isJsonString($str): bool
    {
        try {
            //校验json格式
            json_decode($str, true);
            return JSON_ERROR_NONE === json_last_error();
        } catch (WorkFlowException $e) {
            return false;
        }
    }

    /**
     * 对象或数组转json字符串
     *
     * @param object|array $object
     *
     * @return string
     */
    public static function toJson(object|array $object): string
    {
        if ($object == null) return "";
        try {
            return json_encode($object);
        } catch (\Exception $e) {
            return "";
        }
    }

    /**
     * 根据指定类型解析json字符串，并返回该类型的对象
     *
     * @param string $jsonString
     * @param bool   $associative
     *
     * @return object|array|null
     */
    public static function fromJson(string $jsonString, bool $associative = false): object|array|null
    {
        if (StringHelper::isEmpty($jsonString)) {
            return null;
        }
        try {
            return json_decode($jsonString, $associative);
        } catch (\Exception $e) {
            return null;
        }
    }
}
